package com.situ.company.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.company.dao.impl.UserRoleDaoImpl;
import com.situ.company.entity.Department;
import com.situ.company.entity.Role;
import com.situ.company.entity.User;
import com.situ.company.service.IDepartmentService;
import com.situ.company.service.IRoleService;
import com.situ.company.service.IUserRoleService;
import com.situ.company.service.IUserService;
import com.situ.company.service.impl.DepartmentServiceImpl;
import com.situ.company.service.impl.RoleServiceImpl;
import com.situ.company.service.impl.UserRoleServiceImpl;
import com.situ.company.service.impl.UserServiceImpl;
import com.situ.company.util.JSONResult;
import com.situ.company.util.JSONUtil;
import com.situ.company.vo.PageInfo;

import net.sf.json.JSONObject;

@WebServlet("/user")
public class UserServlet extends HttpServlet{
	private IUserService userService = new UserServiceImpl();
	private IDepartmentService departmentService = new DepartmentServiceImpl();
	private IRoleService roleService = new RoleServiceImpl();
	private IUserRoleService userRoleService = new UserRoleServiceImpl();
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		
		// 判断用户有没有登录根据session里面有没有user对象
//		HttpSession session = req.getSession();
//		User user = (User) session.getAttribute("user");
//		if (user == null) {
//			resp.sendRedirect(req.getContextPath() + "/login.jsp");
//			return;
//		}
		
		
		if (method == null || "".equals(method)) {
			method = "selectLayuiByPage";
		}
		switch (method) {
		case "selectAll":
			selectAll(req, resp);
			break;
		case "selectByPage":
			selectByPage(req, resp);
			break;
		case "selectLayuiByPage":
			selectLayuiByPage(req, resp);
			break;
		case "deleteById":
			deleteById(req, resp);
			break;
		case "deleteAll":
			deleteAll(req, resp);
			break;
		case "login":
			login(req, resp);
			break;
		case "logout":
			logout(req, resp);
			break;
		case "getUserInsertPage":
			getUserInsertPage(req, resp);
			break;
		case "getUserUpdatePage":
			getUserUpdatePage(req, resp);
			break;
		case "insert":
			insert(req, resp);
			break;
		case "update":
			update(req, resp);
			break;
		default:
			break;
		}
		
	}

	private void update(HttpServletRequest req, HttpServletResponse resp) {
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String password = req.getParameter("password");
		String email = req.getParameter("email");
		String departmentId = req.getParameter("departmentId");
		String[] roleIds = req.getParameterValues("roleIds");
		
		User user = new User(Integer.parseInt(id), name, password, email, Integer.parseInt(age), Integer.parseInt(departmentId)); 
		
		boolean isOk = userService.update(user, roleIds);
		JSONResult jsonResult = null;
		if (isOk) {
			jsonResult = new JSONResult(JSONResult.OK, "修改成功");
		} else {
			jsonResult = new JSONResult(JSONResult.ERROR, "修改失败");
		}
		
		JSONUtil.obj2Json(jsonResult, resp);
	}

	private void getUserUpdatePage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		User user = userService.selectById(Integer.parseInt(id));
		req.setAttribute("user", user);
		
		List<Department> departmentList = departmentService.selectAll();
		req.setAttribute("departmentList", departmentList);
		
		// 所有角色的List
		List<Role> roleList = roleService.selectAll();
		
		// 当前User选择的所有角色的id就可以
		List<Integer> selectedRoleIdList = userRoleService.selectRoleIdByUserId(Integer.parseInt(id));
		// req.setAttribute("selectedRoleIdList", selectedRoleIdList);
		// 2,3
		for (Integer selectId : selectedRoleIdList) {
			// 1,2,3
			for (Role role : roleList) {
				if (selectId == role.getId()) {
					role.setChecked(true);
				}
			}
		}
		req.setAttribute("roleList", roleList);
		
		req.getRequestDispatcher("/user_update.jsp").forward(req, resp);
		
	}

	private void deleteAll(HttpServletRequest req, HttpServletResponse resp) {
		// "1,2,44"
		// String[] ids = "1,2,44".split(",");
		String[] ids = req.getParameterValues("ids[]");
		boolean isOk = userService.deleteAll(ids);
		JSONResult jsonResult = null;
		if (isOk) {
			jsonResult = new JSONResult(JSONResult.OK, "删除成功");
		} else {
			jsonResult = new JSONResult(JSONResult.ERROR, "删除失败");
		}
		
		JSONUtil.obj2Json(jsonResult, resp);
	}

	private void insert(HttpServletRequest req, HttpServletResponse resp) {
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String password = req.getParameter("password");
		String email = req.getParameter("email");
		String departmentId = req.getParameter("departmentId");
		String[] roleIds = req.getParameterValues("roleIds");
		
		User user = new User(name, password, email, Integer.parseInt(age), Integer.parseInt(departmentId)); 
		
		boolean isOk = userService.insert(user, roleIds);
		JSONResult jsonResult = null;
		if (isOk) {
			jsonResult = new JSONResult(JSONResult.OK, "添加成功");
		} else {
			jsonResult = new JSONResult(JSONResult.ERROR, "添加失败");
		}
		
		JSONUtil.obj2Json(jsonResult, resp);
	}

	private void getUserInsertPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Department> departmentList = departmentService.selectAll();
		req.setAttribute("departmentList", departmentList);
		
		List<Role> roleList = roleService.selectAll();
		req.setAttribute("roleList", roleList);
		
		req.getRequestDispatcher("/user_insert.jsp").forward(req, resp);
	}

	private void selectLayuiByPage(HttpServletRequest req, HttpServletResponse resp) {
		List<User> list = new ArrayList<User>();
//		list.add(new User(1, "张三1", "123", "123", 12));
//		list.add(new User(2, "张三2", "123", "123", 12));
//		list.add(new User(3, "张三3", "123", "123", 12));
//		list.add(new User(4, "张三4", "123", "123", 12));
//		list.add(new User(5, "张三5", "123", "123", 12));
//		list.add(new User(6, "张三6", "123", "123", 12));
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("code", 0);
//		map.put("count", 192);
//		map.put("msg", "");
//		map.put("data", list);
//		
//		JSONUtil.obj2Json(map, resp);
		
		//JSONResult jsonResult = new JSONResult(0, "", list, 192);
		//JSONUtil.obj2Json(jsonResult, resp);
		
		// http://localhost:8080/Company/user?method=selectLayuiByPage&page=1&limit=10
		String page = req.getParameter("page");
		String limit = req.getParameter("limit");
		// /Company/user?method=selectLayuiByPage&page=1&limit=10&name=55
		String name = req.getParameter("name");
		if (name == null) {
			name = "";// '%null%' 变为 '%%'就是搜索所有
		}
		JSONResult jsonResult = userService.selectLayuiByPage(name, Integer.parseInt(page), Integer.parseInt(limit));
		JSONUtil.obj2Json(jsonResult, resp);
	}

	private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		HttpSession session = req.getSession(false);
		if (session != null) {
			session.invalidate();
			
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
		}
	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		User user = userService.login(name, password);
		
		if (user != null) {// 当前用户登录成功
			HttpSession session = req.getSession();
			session.setAttribute("user", user);
			
			resp.sendRedirect(req.getContextPath() + "/user");
		} else {
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
		}
	}

	private void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// /user?method=selectByPage&pageNo=1&pageSize=10
		String pageNo = req.getParameter("pageNo");
		String pageSize = req.getParameter("pageSize");
		if (pageNo == null || "".equals(pageNo)) {
			pageNo = "1";
		}
		if (pageSize == null || "".equals(pageSize)) {
			pageSize = "3";
		}
		
		PageInfo pageInfo = userService.selectByPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
		System.out.println(pageInfo);
		req.setAttribute("pageInfo", pageInfo);
		req.getRequestDispatcher("/user_page_list.jsp").forward(req, resp);
	}

	private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id");
		
		boolean isOk = userService.deleteById(Integer.parseInt(id));
		
		// 302+location
		// resp.sendRedirect(req.getContextPath() + "/user?method=selectByPage");
		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("isOk", isOk);
//		map.put("msg", "刪除成功");
		// {'isOk' : true, 'status' : 0}
//		resp.setContentType("text/html;charset=utf-8");
//		JSONObject jsonObject = JSONObject.fromObject(map);
//		resp.getWriter().write(jsonObject.toString());
		
		//JSONUtil.obj2Json(map, resp);
		
		JSONResult jsonResult = null;
		if (isOk) {
			jsonResult = new JSONResult(JSONResult.OK, "删除成功");
		} else {
			jsonResult = new JSONResult(JSONResult.ERROR, "删除失败");
		}
		
		JSONUtil.obj2Json(jsonResult, resp);
		
	}

	private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<User> list = userService.selectAll();
		
		req.setAttribute("list", list);
		req.getRequestDispatcher("/user_list.jsp").forward(req, resp);
	}
	

}
